﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.Common;

namespace MisClient
{
    public partial class FrmInvoiceSpecial : BaseForm
    {
        private IBLL.IDepart departBLL = MisCLL.DAOFactory.CreateInstance().GetRemoteDepart();
        private IBLL.ISacf sacfBLL = MisCLL.DAOFactory.CreateInstance().GetRemoteSacf();
        private IBLL.ICustomer cusBLL = MisCLL.DAOFactory.CreateInstance().GetRemoteCustomer();
        private IBLL.IFkType typeBLL = MisCLL.DAOFactory.CreateInstance().GetRemoteFkType();
        private IBLL.IGoods goodsBLL = MisCLL.DAOFactory.CreateInstance().GetRemoteGoods();
        private IBLL.ICusDep cusDepBLL = MisCLL.DAOFactory.CreateInstance().GetRemoteCusDep();

        public FrmInvoiceSpecial()
        {
            InitializeComponent();
        }

        private void label26_Click(object sender, EventArgs e)
        {

        }

        private void textBox14_TextChanged(object sender, EventArgs e)
        {

        }

        private void FrmInvoiceSpecial_Load(object sender, EventArgs e)
        {
            this.openStarDate.Value = DateTime.Now.Date.AddDays(-120);
            this.expireStarDate.Value = DateTime.Now.Date.AddDays(-7);
            this.expireEndDate.Value = DateTime.Now.Date.AddDays(7);
            this.txtDepCode.Text = accountUser.DeptCode;
            this.openStarDate.Focus();
        }

        private void btnQuit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            Dictionary<string, object> dictionary = new Dictionary<string, object>();
            StringBuilder sb = new StringBuilder();
            sb.Append(" and m.date>=@startDate and m.date<=@endDate");
            dictionary.Add("@startDate", this.openStarDate.Value.ToShortDateString());
            dictionary.Add("@endDate", this.openEndDate.Value.ToShortDateString());
            sb.Append(" and (m.sl<0 and (m.date_js>=@gqStartDate and m.date_js<=@gqEndDate))");
            dictionary.Add("@gqStartDate", this.expireStarDate.Value.ToShortDateString());
            dictionary.Add("@gqEndDate", this.expireEndDate.Value.ToShortDateString());
            if (string.IsNullOrEmpty(this.txtDepCode.Text.Trim()))
            {
                MessageBox.Show("部门代码不能为空！", "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                this.txtDepCode.Focus();
                return;
            }
            if (this.txtDepCode.Text.Trim().Length<2)
            {
                MessageBox.Show("部门代码长度为2！", "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                this.txtDepCode.Focus();
                return;
            }
            MisModel.Depart depart = departBLL.GetById(this.txtDepCode.Text.Trim());
            if (depart == null)
            {
                MessageBox.Show("此部门无权操作！", "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                this.txtDepCode.Focus();
                return;
            }
            sb.Append(" and m.dep_id=@depId");
            dictionary.Add("@depId", this.txtDepCode.Text.Trim());
            if (string.IsNullOrEmpty(this.txtCusCode.Text.Trim()))
            {
                MessageBox.Show("请输入客户代码！", "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                this.txtCusCode.Focus();
                return;
            }
            this.dataGridView1.Rows.Clear();
            sb.Append(" and m.cus_id=@cusId");
            dictionary.Add("@cusId", this.txtCusCode.Text.Trim());
            if (!string.IsNullOrEmpty(this.txtCusDepCode.Text.Trim()))
            {
                sb.Append(" and m.cus_dep=@cusDep");
                dictionary.Add("@cusDep", this.txtCusDepCode.Text.Trim());
            }
            if (!string.IsNullOrEmpty(this.txtCusShopCode.Text.Trim()))
            {
                sb.Append(" and m.type_js=@typeJs");
                dictionary.Add("@typeJs", this.txtCusShopCode.Text.Trim());
            }
            if (!string.IsNullOrEmpty(this.txtID.Text.Trim()))
            {
                sb.Append(" and m.id=@id");
                dictionary.Add("@id", this.txtID.Text.Trim());
            }
            if (!string.IsNullOrEmpty(this.txtNo.Text.Trim()))
            {
                sb.Append(" and m.no=@no");
                dictionary.Add("@no", this.txtNo.Text.Trim());
            }
            if (!string.IsNullOrEmpty(this.txtTax.Text.Trim()))
            {
                sb.Append(" and m.tax=@tax");
                dictionary.Add("@tax", this.txtTax.Text.Trim());
            }
            if ("已提货,未开发票".Equals(this.comboBox1.SelectedItem.ToString()))
                sb.Append(" and m.f2='1' and m.f3=''");
            else if ("未提货,未开发票".Equals(this.comboBox1.SelectedItem.ToString()))
                sb.Append(" and m.f2='' and m.f3=''");
            else if ("已开发票".Equals(this.comboBox1.SelectedItem.ToString()))
                sb.Append(" and m.f2!='0' and m.f3='1'");
            else
                sb.Append(" and m.f2!='0' and m.f3=''");
            if (!string.IsNullOrEmpty(this.txtType1.Text.Trim()))
            {
                sb.Append(" and m.type1=@type1");
                dictionary.Add("@type1", this.txtType1.Text.Trim());
            }
            if (!string.IsNullOrEmpty(this.txtType2.Text.Trim()))
            {
                sb.Append(" and m.type2=@type2");
                dictionary.Add("@type2", this.txtType2.Text.Trim());
            }
            if (!string.IsNullOrEmpty(this.txtType3.Text.Trim()))
            {
                sb.Append(" and m.type3=@type3");
                dictionary.Add("@type3", this.txtType3.Text.Trim());
            }
            DataTable dt=sacfBLL.GetAll(sb.ToString(), dictionary);
            if (dt != null && dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    String[] DataRow = new String[34];
                    DataRow[1] = dt.Rows[i]["no"].ToString();
                    DataRow[2] = dt.Rows[i]["shop_id"].ToString();
                    DataRow[3] = string.Format("{0} {1} {2}", dt.Rows[i]["dep_id"].ToString(), dt.Rows[i]["id"].ToString(), dt.Rows[i]["goods"].ToString());
                    DataRow[4] = dt.Rows[i]["sl_p"].ToString();
                    DataRow[5] = dt.Rows[i]["sl"].ToString();
                    DataRow[6] = dt.Rows[i]["je_hs"].ToString();
                    DataRow[7] = dt.Rows[i]["f1"].ToString();
                    DataRow[8] = dt.Rows[i]["f2"].ToString();
                    DataRow[9] = dt.Rows[i]["f3"].ToString();
                    DataRow[10] = dt.Rows[i]["f4"].ToString();
                    DataRow[11] = dt.Rows[i]["f8"].ToString();
                    DataRow[12] = dt.Rows[i]["date"].ToString();
                    DataRow[13] = dt.Rows[i]["d_th"].ToString();
                    DataRow[14] = dt.Rows[i]["d_kp"].ToString();
                    DataRow[15] = dt.Rows[i]["d_js"].ToString();
                    DataRow[16] = dt.Rows[i]["d_ok"].ToString();
                    DataRow[17] = dt.Rows[i]["date_js"].ToString();
                    DataRow[18] = dt.Rows[i]["type_js"].ToString();
                    DataRow[19] = dt.Rows[i]["day_js"].ToString();
                    DataRow[20] = string.Format("{0} {1} {2}", dt.Rows[i]["cus_id"].ToString(), dt.Rows[i]["cus_dep"].ToString(), dt.Rows[i]["cus_shop"].ToString());
                    DataRow[21] = dt.Rows[i]["no_cus"].ToString();
                    DataRow[22] = dt.Rows[i]["price_fs"].ToString();
                    DataRow[23] = dt.Rows[i]["je_fs"].ToString();
                    DataRow[24] = dt.Rows[i]["price_hs"].ToString();
                    DataRow[25] = dt.Rows[i]["nono"].ToString();
                    DataRow[26] = dt.Rows[i]["dm"].ToString();
                    DataRow[27] = dt.Rows[i]["unit"].ToString();
                    DataRow[28] = dt.Rows[i]["oper"].ToString();
                    DataRow[29] = dt.Rows[i]["op_kp"].ToString();
                    DataRow[30] = dt.Rows[i]["je_fs"].ToString();
                    DataRow[31] = dt.Rows[i]["tax"].ToString();
                    DataRow[32] = dt.Rows[i]["cus_dep"].ToString();
                    DataRow[33] = dt.Rows[i]["id"].ToString();
                    this.dataGridView1.Rows.Add(DataRow);
                }
                this.btnRef.Enabled = true;
                this.btnPri.Enabled = true;
                this.btnCal.Enabled = true;
                this.btnSave.Enabled = true;
            }else
            {
                MessageBox.Show("查无符合条件的记录！", "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(this.txtInvoiceNum.Text.Trim()))
            {
                MessageBox.Show("请输入原始发票号！", "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                this.txtInvoiceNum.Focus();
                return;
            }
            if (string.IsNullOrEmpty(this.txtInvoiceCode.Text.Trim()))
            {
                MessageBox.Show("整张发票合计金额为：", "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                this.txtInvoiceCode.Focus();
                return;
            }
            string goods = "无金额调整";
            decimal cas = 0;
            string f7 = "0";
            decimal hj = decimal.Parse(this.lbHsje.Text.Trim());
            decimal nhj = decimal.Parse(this.lbWsje.Text.Trim());
            if (hj <= 0)
            {
                MessageBox.Show(string.Format("整张发票合计金额为：{0}\n小于零，不可操作！", hj), "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                this.txtInvoiceCode.Focus();
                return;
            }
            if (!string.IsNullOrEmpty(this.txtReviseJe.Text.Trim()) && !"0".Equals(this.txtReviseJe.Text.Trim()))
            {
                if (!"17".Equals(this.txtReviseSl.Text.Trim()) && !"13".Equals(this.txtReviseSl.Text.Trim()))
                {
                    MessageBox.Show("有金额调整,税率应为17或13！", "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    this.txtReviseSl.Focus();
                    return;
                }
                hj += decimal.Parse(this.txtReviseJe.Text.Trim());
                if (hj <= 0)
                {
                    MessageBox.Show(string.Format("有金额调整，整张发票合计金额为：{0}\n小于零，不可操作！", hj), "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    this.txtReviseSl.Focus();
                    return;
                }
                nhj += decimal.Parse(this.txtReviseJe.Text.Trim()) * 100 / (100 + decimal.Parse(this.txtReviseSl.Text.Trim()));
                goods = string.Format("*{0}税{1} {2}", this.txtReviseJe.Text.Trim(), this.txtReviseSl.Text.Trim(), this.txtReviseNr.Text.Trim());
                cas = decimal.Parse(this.txtReviseJe.Text.Trim());
                f7 = "1";
                if (MessageBox.Show(string.Format("有金额调整，整张发票合计金额为：{0}\n请检查各项目是否正确，是否保存[Y/N]？", hj), "提问窗", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                    return;
            }
            else
            {
                if (MessageBox.Show("无金额调整，\n请检查各项目是否正确，是否保存[Y/N]？", "提问窗", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                    return;
            }
            MisEntity.Invoice invoice = new MisEntity.Invoice();
            invoice.je_hs = hj;
            invoice.je_fs = nhj;
            invoice.OPER = accountUser.UserCode;
            invoice.bei = this.txtInvoiceNum.Text.Trim();
            invoice.goods = goods;
            invoice.je_cas = cas;
            invoice.DM = this.txtCusCode.Text.Trim();
            invoice.ID = this.txtCusDepCode.Text.Trim();
            if (this.dataGridView1.Rows.Count > 0)
            {
                IList<MisEntity.Sacf> list = new List<MisEntity.Sacf>(this.dataGridView1.Rows.Count);
                DataGridViewRow dr = null;
                MisEntity.Sacf entity = null;
                int count = 0;
                for (int i = 0; i < this.dataGridView1.Rows.Count; i++)
                {
                    dr = this.dataGridView1.Rows[i];
                    Boolean dataSel = Convert.ToBoolean(dr.Cells["dataSel"].FormattedValue);
                    if (dataSel)
                    {
                        string f2 = dr.Cells["data8"].Value.ToString();
                        string f3 = dr.Cells["data9"].Value.ToString();
                        if ("1".Equals(f2.Trim()) && "".Equals(f3.Trim()))
                        {

                            entity = new MisEntity.Sacf();
                            entity.NO = dr.Cells["data1"].Value.ToString();
                            entity.NONO = decimal.Parse(dr.Cells["data25"].Value.ToString());
                            entity.ID = dr.Cells["id"].Value.ToString();
                            entity.OP_KP =accountUser.UserCode;
                            entity.NO_CUS = this.txtInvoiceNum.Text.Trim();
                            entity.F7 = char.Parse(f7);
                            list.Add(entity);
                            count++;
                        }
                        else
                        {
                            MessageBox.Show("并非均为已提货且未开发票，不可保存！", "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            return;
                        }
                    }
                }
                if (count <= 0)
                {
                    MessageBox.Show("请先选择发票！", "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                sacfBLL.Billing(invoice, list);
                MessageBox.Show("存盘结束！", "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                this.btnRef.Enabled = false;
                this.btnPri.Enabled = false;
                this.btnCal.Enabled = false;
                this.btnSave.Enabled = false;
            }
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 0)
            {
                DataGridViewRow dr = this.dataGridView1.Rows[e.RowIndex];
                bool isEditSel = Convert.ToBoolean(dr.Cells[e.ColumnIndex].EditedFormattedValue);
                if (isEditSel)
                {
                    this.lbHsje.Text = (decimal.Parse(dr.Cells["data6"].Value.ToString()) + decimal.Parse(this.lbHsje.Text.ToString())).ToString();
                    this.lbWsje.Text = (decimal.Parse(dr.Cells["data23"].Value.ToString()) + decimal.Parse(this.lbWsje.Text.ToString())).ToString();
                }
                else
                {
                    this.lbHsje.Text = (decimal.Parse(this.lbHsje.Text.ToString())-decimal.Parse(dr.Cells["data6"].Value.ToString())).ToString();
                    this.lbWsje.Text = (decimal.Parse(this.lbWsje.Text.ToString())-decimal.Parse(dr.Cells["data23"].Value.ToString())).ToString();
                }
                this.label8.Text = string.Format("●合计开票 含税金额：{0} 未税金额：{1}", this.lbHsje.Text.ToString(), this.lbWsje.Text.ToString());
                return;
            }
        }

        private void openStarDate_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.openEndDate.Focus();
            }
        }

        private void openEndDate_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.txtDepCode.Focus();
            }
        }

        private void txtDepCode_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (string.IsNullOrEmpty(this.txtDepCode.Text.Trim()))
                {
                    MessageBox.Show("部门代码不能为空！", "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    this.txtDepCode.Focus();
                    return;
                }
                if (this.txtDepCode.Text.Trim().Length<2)
                {
                    MessageBox.Show("部门代码长度为2！", "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    this.txtDepCode.Focus();
                    return;
                }
                MisModel.Depart depart = departBLL.GetById(this.txtDepCode.Text.Trim());
                if (depart == null)
                {
                    MessageBox.Show("此部门无权操作！", "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    this.txtDepCode.Focus();
                    return;
                }
                this.txtBoxDep.Text = depart.DepName;
                this.txtCusCode.Focus();
            }
        }

        private void txtCusCode_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (string.IsNullOrEmpty(this.txtCusCode.Text.Trim()))
                {
                    MessageBox.Show("请输入客户代码！", "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    this.txtCusCode.Focus();
                    return;
                }
                MisModel.Customer customer = cusBLL.GetById(this.txtCusCode.Text.Trim());
                if (customer == null)
                {
                    MessageBox.Show("无此代码或不属于本部分！", "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    this.txtCusCode.Focus();
                    return;
                }
                this.txtBoxCus.Text = customer.Customer_;
                this.txtInvoiceNum.Focus();
            }
        }

        private void txtInvoiceNum_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.comboBox1.Focus();
            }
        }

        private void comboBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.btnOk.Focus();
            }
        }

        private void expireStarDate_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.expireEndDate.Focus();
            }
        }

        private void expireEndDate_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.txtCusShopCode.Focus();
            }
        }

        private void txtCusShopCode_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (!string.IsNullOrEmpty(this.txtCusShopCode.Text.Trim()))
                {
                    MisModel.FKType fkType = typeBLL.GetById(this.txtCusShopCode.Text.Trim());
                    if(fkType==null)
                    {
                        MessageBox.Show("无此代码或不属于此结算类型！", "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        this.txtCusShopCode.Focus();
                        return;
                    }
                    this.txtBoxCusShop.Text=fkType.FkType;
                }
                this.txtNo.Focus();
            }
        }

        private void txtNo_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.txtTax.Focus();
            }
        }

        private void txtTax_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.txtID.Focus();
            }
        }

        private void txtID_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (!string.IsNullOrEmpty(this.txtID.Text.Trim()))
                {
                    MisEntity.Goods goods = goodsBLL.EndsWithID(this.txtID.Text.Trim());
                    if (goods == null)
                    {
                        MessageBox.Show("无此商品,请先设置！", "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        this.txtID.Focus();
                        return;
                    }
                    this.txtGoods.Text=goods.GOODS;
                    this.txtDM.Text = goods.DM;
                }
                this.btnOk.Focus();
            }
        }

        private void txtReviseNr_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.txtNo.Focus();
            }
        }

        private void txtReviseSl_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.txtReviseJe.Focus();
            }
        }

        private void txtReviseJe_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.txtCusDepCode.Focus();
            }
        }

        private void txtCusDepCode_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (!string.IsNullOrEmpty(this.txtCusDepCode.Text.Trim()))
                {
                    MisModel.CusDep cusDep = cusDepBLL.GetById(this.txtCusCode.Text.Trim());
                    if (cusDep == null)
                    {
                        MessageBox.Show("客户部门代码不存在,或无权操作！", "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        this.txtCusDepCode.Focus();
                        return;
                    }
                    else
                    {
                        this.txtBoxCusDep.Text = cusDep.Depart;
                        this.txtInvoiceNum.Focus();
                    }
                }
            }
        }
    }
}
